package cn.zktr.Personnel.model.service.zhouxiong;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.zktr.Personnel.common.DateListString;
import cn.zktr.Personnel.common.TimeStamp;
import cn.zktr.Personnel.model.dao.zhouxiong.*;
import cn.zktr.Personnel.model.mappers.zhouxiong.*;
import cn.zktr.Personnel.model.mappers.zhouyongcong.getUitlsMapper;
import cn.zktr.Personnel.model.pojos.*;
import cn.zktr.Personnel.model.service.zhouyongcong.findService;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;

@Service
@Transactional(rollbackOn=Exception.class)
public class KaoQinKaService {
	
	@Autowired
	private CwaKprMapper kpr;	//排班
	@Autowired
	private CwaKprDAO kprD;	//排班

	@Autowired
	private CwaCwasDAO cwaD;	//考勤卡
	@Autowired
	private CwaCwasMapper cwa;	//考勤卡

	@Autowired
	private CwaTemDAO temD;	//考勤卡
	
	@Autowired
	public CwaResDAO resD;	//考勤数据
	@Autowired
	public CwaResMapper resM;	//考勤数据

	@Autowired
	public CwaQLaeMapper laeM;	//考勤数据
	
	@Autowired
	public NoimpService Noimp;
	

	@Autowired
	private KaoQinKaService kqk;
	@Autowired
	private JiChuService jichu;
	@Autowired
	private findService fs;
	

	@Autowired
	public getUitlsMapper uitlM;	//考勤数据
	
	public JSONArray selectDept() {
		try {
			return cwa.selectDept();
		} catch (Exception e) {
			return null;
		}
	}

	//***********************排班*********************************88
	/**排班列表
	 * @return
	 */
	public JSONArray selePaiBan() {
		try {
			return kpr.selePaiBan("%%");
		} catch (Exception e) {
			return null;
		}
	}
	public JSONArray selePaiBan(String Str) {
		try {
			return kpr.selePaiBan("%"+Str+"%");
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public void tiaobanUP(Integer cwasid,String[] jsons) {
		for (int i = 0; i < jsons.length; i++) {
			System.err.println(jsons[i]);
			updatePB( cwasid, Integer.valueOf(jsons[i]));
			updatebz(cwasid);
		}
	}
	
	/**排班 更新
	 * @param kpr
	 */
	public void updatePB(Integer cwasid,Integer empid) {
		try {
			PerCwaKpr kpr = new PerCwaKpr();
			kpr.setPerCwaCwa(kqk.findByCwasId(cwasid));
			kpr.setPerPmsEmp(fs.findEmpid(empid));
			kpr.setKprtime(new TimeStamp().getNetworkTime());
			kprD.save(kpr);
			return;
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public void updatebz(Integer cwasid) {
		try {
			PerCwaCwas cwas = cwaD.findById(cwasid).get();
			PerCwaTem tem = cwas.getPerCwaTem();
			tem.setTemrs(tem.getTemrs()+1);
			System.err.println("人数变动："+tem.getTemrs());
			temD.save(tem);
			return;
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public void updatebz(Integer cwasid,Integer empidsl) {
		try {
			PerCwaCwas cwas = cwaD.findById(cwasid).get();
			PerCwaTem tem = cwas.getPerCwaTem();
			tem.setTemrs(tem.getTemrs()+empidsl);
			System.err.println("人数变动："+tem.getTemrs());
			temD.save(tem);
			return;
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	/**删除
	 * @param kprid
	 */
	public void deletePB(Integer kprid) {
		try {
			kprD.deleteById(kprid);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	/**根据部门查员工
	 * @param deptid
	 * @return
	 */
	public JSONArray deptemp(Integer cwasid) {
		try {
			return uitlM.selEmpDeptId(cwaD.findById(cwasid).get().getPerPmsDept().getDeptid());
		} catch (Exception e) {
			return null;
		}
	}
	
	
	//***************************考勤*********************************
	/**考勤卡
	 * @return
	 */
	public JSONArray seleKaoQinKa() {
		try {
			return cwa.seleKaoQinKa();
		} catch (Exception e) {
			return null;
		}
	}
	
	/**考勤卡下面的人员
	 * @return
	 */
	public JSONArray KaoQinRenYuan(Integer CWASID) {
		try {
			return cwa.KaoQinRenYuan(CWASID);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**根据id 查 考勤卡
	 * @param cwasid
	 * @return
	 */
	public PerCwaCwas findByCwasId(Integer cwasid) {
		try {
			return cwaD.findById(cwasid).get();
		} catch (Exception e) {
			return null;
		}
	}
	
	/**根据员工id 查 考勤卡
	 * @param cwasid
	 * @return
	 */
	public PerCwaCwas findByEmpid(Integer empid) {
		try {
			return cwa.findByEmpid(empid);
		} catch (Exception e) {
			return null;
		}
	}
	
	/**考勤卡 新增修改
	 * @param cwa
	 */
	public void addKaoQinKa(Integer cwasid,Integer temid,Integer shfid,Integer empid,Integer rsnid,String cwasrem) {
		try {
			PerCwaCwas cwa = new PerCwaCwas();
			if(cwasid!=null) {
				cwa.setCwasid(cwasid);
			}
			cwa.setPerPmsDept(temD.findById(temid).get().getPerPmsDept());
			cwa.setPerCwaTem(jichu.findByBanZuId(temid));
			cwa.setPerCwaShf(jichu.findByBanCiId(shfid));
			cwa.setPerPmsEmp(fs.findEmpid(empid));
			cwa.setPerCwaRsn(jichu.findByYuanYinId(rsnid));
			cwa.setCwasrem(cwasrem);
			cwa.setCwastime(new TimeStamp().getNetworkTime());
			cwaD.save(cwa);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	
	//************************考勤数据**********************
	/**员工考勤数据
	 * @param empid
	 * @param DATE
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public List<JSONObject> seleYuanGongKaoQin(Integer empid) {
		try {
			List<JSONObject> dates = new ArrayList<>();
			JSONArray lb = resM.selKaoQinShiJieLieBiaos(empid);
			for (int i = 0; i < lb.size(); i++) {
				JSONObject ShuJu = resM.seleKaoQinShuJu(empid,1);
//				System.err.println("员工："+empid+","+s);
				Timestamp RESMINTIME = resM.KaoQinShuJuQianZhi1_RESMINTIME(empid, lb.getJSONObject(i).getString("RESTIME"), 1);
				Timestamp RESMAXTIME = resM.KaoQinShuJuQianZhiQianZhi2_RESMAXTIME(empid, lb.getJSONObject(i).getString("RESTIME"), 1);
				Integer RESTIME = resM.KaoQinShuJuQianZhiQianZhi3_RESTIME(empid, lb.getJSONObject(i).getString("RESTIME"), 1);
				if(RESMINTIME!=null && RESMAXTIME!=null && RESTIME!=null) {
					ShuJu.put("RESMINTIME", RESMINTIME);
					ShuJu.put("RESMAXTIME", RESMAXTIME);
					ShuJu.put("RESTIME", RESTIME);
					
					String date1 = ShuJu.getString("SHFTIME").split("-")[0]+":00";
					String date2 = ShuJu.getString("SHFTIME").split("-")[1]+":00";
					
					String min1 = RESMINTIME.getHours()+":"+RESMINTIME.getMinutes()+":"+RESMINTIME.getSeconds();
					String min2 = RESMAXTIME.getHours()+":"+RESMAXTIME.getMinutes()+":"+RESMAXTIME.getSeconds();

					int s1 = dateBiJiao(date1,min1);
					int s2 = dateBiJiao(date2,min2);
					String sum="";
					if(s1==0){
						sum += "(迟到)";
					}else {
						sum += "(正常)";
					}
					if(s2==1){
						sum += "(早退)";
					}else {
						sum += "(正常)";
					}
					
					ShuJu.put("CWAJG", sum);

					dates.add(ShuJu);
				}
			}
			return dates;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**员工考勤数据
	 * @param empid
	 * @param DATE
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public List<JSONObject> seleYuanGongKaoQin(Integer empid,String date) {
		try {
			List<JSONObject> dates = new ArrayList<>();
			JSONArray lb = resM.selKaoQinShiJieLieBiao(empid,date);
			for (int i = 0; i < lb.size(); i++) {
				JSONObject ShuJu = resM.seleKaoQinShuJu(empid,1);
//				System.err.println("员工："+empid+","+s);
				Timestamp RESMINTIME = resM.KaoQinShuJuQianZhi1_RESMINTIME(empid, lb.getJSONObject(i).getString("RESTIME"), 1);
				Timestamp RESMAXTIME = resM.KaoQinShuJuQianZhiQianZhi2_RESMAXTIME(empid, lb.getJSONObject(i).getString("RESTIME"), 1);
				Integer RESTIME = resM.KaoQinShuJuQianZhiQianZhi3_RESTIME(empid, lb.getJSONObject(i).getString("RESTIME"), 1);
				if(RESMINTIME!=null && RESMAXTIME!=null && RESTIME!=null) {
					ShuJu.put("RESMINTIME", RESMINTIME);
					ShuJu.put("RESMAXTIME", RESMAXTIME);
					ShuJu.put("RESTIME", RESTIME);
					
					String date1 = ShuJu.getString("SHFTIME").split("-")[0]+":00";
					String date2 = ShuJu.getString("SHFTIME").split("-")[1]+":00";
					
					String min1 = RESMINTIME.getHours()+":"+RESMINTIME.getMinutes()+":"+RESMINTIME.getSeconds();
					String min2 = RESMAXTIME.getHours()+":"+RESMAXTIME.getMinutes()+":"+RESMAXTIME.getSeconds();

					int s1 = dateBiJiao(date1,min1);
					int s2 = dateBiJiao(date2,min2);
					String sum="";
					if(s1==0){
						sum += "(迟到)";
					}else {
						sum += "(正常)";
					}
					if(s2==1){
						sum += "(早退)";
					}else {
						sum += "(正常)";
					}
					
					ShuJu.put("CWAJG", sum);

					dates.add(ShuJu);
				}
			}
			return dates;
		} catch (Exception e) {
			return null;
		}
	}
	
	/**时间比较 先后
	 * 0 date1<date2  1 date1>date2   3 date1=date2 -1比较失败
	 * @param date1
	 * @param date2
	 * @return
	 */
	public int dateBiJiao(String date1,String date2) {
		try {
			String[] date3 =date1.split(":");
			String[] date4 =date2.split(":");
			if(Integer.valueOf((date3[0]))>Integer.valueOf(date4[0])){
				return 1;
			}else if(Integer.valueOf(date3[0])==Integer.valueOf(date4[0])){
				if(Integer.valueOf(date3[1])>Integer.valueOf(date4[1])){
					return 1;
				}else if(Integer.valueOf(date3[1])==Integer.valueOf(date4[1])){
					if(Integer.valueOf(date3[2])>Integer.valueOf(date4[2])){
						return 1;
					}else if(Integer.valueOf(date3[2])==Integer.valueOf(date4[2])){
						return 3;
					}else if(Integer.valueOf(date3[2])<Integer.valueOf(date4[2])){
						return 0;
					}
				}else if(Integer.valueOf(date3[1])<Integer.valueOf(date4[1])){
					return 0;
				}
			}else if(Integer.valueOf(date3[0])<Integer.valueOf(date4[0])){
				return 0;
			}
			return -1;
		} catch (Exception e) {
			return 0;
		}
	}
	
	
	/**考勤数据 根据 年月查询全部数据   2019-1
	 * @return
	 */
	public JSONArray seleKaoQinShuJu(String date) {
		try {
			JSONArray ry = resM.KaoQinShuJuQianZhi_KaoQinRenYuan();
//			List<JSONObject> dates = new ArrayList<>();
			JSONArray dates = new JSONArray();
			for (int i = 0; i < ry.size(); i++) {
				JSONArray lb = resM.selKaoQinShiJieLieBiao(ry.getJSONObject(i).getInteger("EMPID"),date);
				for (int j = 0; j < lb.size(); j++) {
					JSONObject seleKaoQinShuJu = resM.seleKaoQinShuJu(ry.getJSONObject(i).getInteger("EMPID"),1);
//					System.err.println("全部："+e+","+s);
					Timestamp RESMINTIME = resM.KaoQinShuJuQianZhi1_RESMINTIME(ry.getJSONObject(i).getInteger("EMPID"), lb.getJSONObject(j).getString("RESTIME"), 1);
					Timestamp RESMAXTIME = resM.KaoQinShuJuQianZhiQianZhi2_RESMAXTIME(ry.getJSONObject(i).getInteger("EMPID"), lb.getJSONObject(j).getString("RESTIME"), 1);
					Integer RESTIME = resM.KaoQinShuJuQianZhiQianZhi3_RESTIME(ry.getJSONObject(i).getInteger("EMPID"), lb.getJSONObject(j).getString("RESTIME"), 1);
					
					if(RESMINTIME!=null && RESMAXTIME!=null && RESTIME!=null ) {
					
						seleKaoQinShuJu.put("RESMINTIME", RESMINTIME);
						seleKaoQinShuJu.put("RESMAXTIME", RESMAXTIME);
						seleKaoQinShuJu.put("RESTIME", RESTIME);

						dates.add(seleKaoQinShuJu);
					}
				}
			}
			return dates;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	
	
	/**考勤数据 根据 年月查询员工全部数据   2019-1
	 * @return
	 */
	public List<JSONObject> seleKaoQinShuJuYuanGong(String date) {
		try {
			JSONArray ry = resM.KaoQinShuJuQianZhi_KaoQinRenYuan();
			List<JSONObject> dates = new ArrayList<>();
			for (int i=0;i<ry.size();i++) {
				long sum = 0;	
				//数据源
				JSONObject sj=null;
				//存储对象
				JSONObject vo = null;
				Integer QDCiShu = resM.selectTongJi(ry.getJSONObject(i).getInteger("EMPID")).getInteger("qdcs");
				JSONArray lb = resM.selKaoQinShiJieLieBiao(ry.getJSONObject(i).getInteger("EMPID"),date);
				for (int j = 0; j < lb.size(); j++) {
					sj = resM.seleKaoQinShuJu(ry.getJSONObject(i).getInteger("EMPID"),1);
//					System.err.println("员工总："+e+","+s);
					Timestamp RESMINTIME = resM.KaoQinShuJuQianZhi1_RESMINTIME(ry.getJSONObject(i).getInteger("EMPID"), lb.getJSONObject(j).getString("RESTIME"), 1);
					Timestamp RESMAXTIME = resM.KaoQinShuJuQianZhiQianZhi2_RESMAXTIME(ry.getJSONObject(i).getInteger("EMPID"), lb.getJSONObject(j).getString("RESTIME"), 1);
					Integer RESTIME = resM.KaoQinShuJuQianZhiQianZhi3_RESTIME(ry.getJSONObject(i).getInteger("EMPID"), lb.getJSONObject(j).getString("RESTIME"), 1);
					

					if(RESMINTIME!=null && RESMAXTIME!=null && RESTIME!=null ) {
						sj.put("RESMINTIME", RESMINTIME);
						sj.put("RESMAXTIME", RESMAXTIME);
						vo = sj;
						//获取当前值
						sum += RESTIME;
						vo.put("RESTIME", sum);
					}
				}
				vo.put("QDCiShu", QDCiShu);
				if(vo!=null) {
					dates.add(vo);
				}
			}
					
			return dates;
		} catch (Exception e) {
			return null;
		}
	}
	
	
	
	/**考勤数据 更新
	 * @param res
	 */
	public String updateKaoQinShuJu(Integer resid,Integer empid,String rsnreason,String resrem) {
		try {
			Timestamp Time = new TimeStamp().getNetworkTime();
			if(laeM.seleQianDaoQinJiaYanZhen(empid, Time).size()>0) {
				return "2"; //已请假
			}
			PerCwaRes res = new PerCwaRes();
			if(resid!=null) {
				res.setResid(resid);
			}
			System.err.println(String.valueOf(Time).split(" ")[0]);
//			Date date = new Date((Time.getYear()+1900)+":"+(Time.getMonth()+1)+":"+(Time.getDate()));
//			System.err.println(date);
			
			if(Noimp.seleJiaBanSFCZ(String.valueOf(Time).split(" ")[0], empid)>0) {
				res.setResstat("0");//加班
			}else {
				res.setResstat("1");//上班
			}
			if(kqk.findByEmpid(empid)==null) {
				System.err.println("根据员工  "+empid+"  查询人查询错误");
				res.setPerCwaCwa(kqk.findByEmpid(1));		//添加考勤卡
				res.setPerPmsEmp(fs.findEmpid(1));		//添加员工
			}else {
				res.setPerCwaCwa(kqk.findByEmpid(empid));   //添加考勤卡
				res.setPerPmsEmp(fs.findEmpid(empid));   //添加员工 
			}
			
			//原因
			if(jichu.findByRsnreason(rsnreason)==null) {
				System.err.println("根据原因查询错误");
				PerCwaRsn rsns = new PerCwaRsn();
				rsns.setRsnreason(rsnreason);
				jichu.updateYY( null, rsnreason, null);
			}
			res.setPerCwaRsn(jichu.findByRsnreason(rsnreason));
			
			res.setRestime(Time);
			
			res.setResrem(resrem);
			
			resD.save(res);
			
			qiandaochengong();
			return res.getResstat(); //返回签到结果   0加班   1上班
		} catch (Exception e) {
			return "-1";
		}
	}

	/**
	 * 签到成功 
	 */
	public void qiandaochengong() {
		try {
			File file = new File("src/main/webapp/static/zx/audio/QianDao.mp3");
			FileInputStream fileInputStream = new FileInputStream(file);
			BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
			Player player = new Player(bufferedInputStream);
			player.play();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (JavaLayerException e) {
			e.printStackTrace();
		}
	}
}
